package com.atguigu.cloud.service;

import com.atguigu.cloud.entities.Pay;
import com.atguigu.cloud.mapper.PayMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;


@Service
@Slf4j
public class PayService0718 {
    public static final String CACHA_KEY_CUSTOMER = "customer:";


    @Resource
    private PayMapper payMapper;
    @Resource
    private RedisTemplate redisTemplate;

    //写操作
    public void addCustomer(Pay customer){
        int i = payMapper.insertSelective(customer);
        if(i > 0) {
            //mysql插入成功，需要重新查询一次将数据捞出来，写进redis
            Pay result = payMapper.selectByPrimaryKey(customer.getId());
            //redis缓存key
            String key = CACHA_KEY_CUSTOMER + customer.getId();
            //捞出来的数据写进redis
            redisTemplate.opsForValue().set(key,result);

        }
    }

    //读操作
    public Pay findCustomerById(Integer customerId) {
        Pay customer = null;

        //缓存redis的key的名称
        String key = CACHA_KEY_CUSTOMER + customer.getId();
        //1.先去redis查询
        customer = (Pay) redisTemplate.opsForValue().get(key);
        //2.redis有直接返回，没有再进去查询mysql
        if(customer == null) {
            // 3. 再去查询我们的mysql
            customer = payMapper.selectByPrimaryKey(customerId);
            //3.1 mysql有，redis无
            if(customer != null) {
                //3.2 把mysql查询出来的数据回写redis，保持一致性
                redisTemplate.opsForValue().set(key,customer);
            }
        }

        return customer;

    }
}
